<?php


namespace app\admin\controller;

use app\common\model\User;
use think\Controller;
use app\common\model\Project as ProjectModel;
use app\common\model\User as UserModel;
use app\common\model\Auth as AuthModel;


class AuthController extends Controller
{
    public function index()
    {
        if ($this->request->isGet()) {
            $auths = AuthModel::all();
            $this->assign('auths', $auths);
            return $this->fetch();
        }
    }


    public function create()
    {
        if ($this->request->isGet()) {
            $projects = ProjectModel::all();
            $this->assign('projects', $projects);
            return $this->fetch();
        }

        $postData = $this->request->param();
        if (empty($postData['rolename'])) {
            return json(['code' => 4000, 'message' => '请填写角色名!']);
        }

        $tmp_data = [
            'name' => $postData['rolename'],
            'remark' => $postData['remark'],
        ];
        // array_diff_key 对比两个数组得出差异的元素。其实就是筛掉指定的元素。
        $postData = array_diff_key($postData, ['rolename' => '', 'remark' => '']);
        $tmp_data['permission'] = json_encode($postData);

        $auth = new AuthModel();
        if ($auth->allowField(true)->validate(true)->save($tmp_data)) {
            return json(['code' => 0, 'message' => '添加成功']);
        }
        // var_dump(json_encode($postData));
        return json(['code' => 4000, 'message' => '添加失败']);
    }


    public function update()
    {
        if ($this->request->isGet()) {
            $auth_id = $this->request->get('id');
            $auth = AuthModel::get($auth_id);
            if (is_null($auth)) {
                return $this->error('角色不存在');
            }
            $projects = ProjectModel::all();
            $this->assign(['projects' => $projects, 'auth' => $auth]);
            return $this->fetch();
        }

        $postData = $this->request->post();
        // print_r($postData);

        if (empty($postData['rolename'])) {
            return json(['code' => 4000, 'message' => '请填写角色名!']);
        }

        $tmp_data = [
            'name' => $postData['rolename'],
            'remark' => $postData['remark'],
        ];
        $auth_id = $postData['id'];

        // array_diff_key 对比两个数组得出差异的元素。其实就是筛掉指定的元素。
        $postData = array_diff_key($postData, ['rolename' => '', 'remark' => '', 'id'=>'']);
        $tmp_data['permission'] = json_encode($postData);

        // print_r($tmp_data);
        // 提交更新数据
        $auth = new AuthModel();
        if ($auth->allowField(true)->isUpdate(true)->save($tmp_data, ['id' => $auth_id])) {
            return json(['code' => 0, 'message' => '更新成功']);
        }
        return json(['code'=> 4000, 'message'=>'更新失败...']);
    }


    public function delete()
    {
        $auth_id = $this->request->get('id');
        $auth = AuthModel::get($auth_id);
        if ($auth->delete()) {
            return json(['code' => 0, 'message' => '删除成功']);
        }

        return json(['code' => 4000, 'message' => '删除失败' . $auth->getError()]);
    }


    /** 为用户分配角色
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function assign_role()
    {
        if ($this->request->isGet()) {
            $uid = $this->request->param('uid');
            if (!isset($uid)) {
                json(['code'=>4000, 'message'=>'没有uid参数']);
            }
            $user = UserModel::get($uid);

            $user_roles = collection($user->auths()->select())->toJson();

            $auths = AuthModel::all();
            $this->assign([
                'auths' => $auths,
                'uid' => $uid,
                'user_roles'=>$user_roles,
            ]);
            return $this->fetch();
        }

        $postData = $this->request->param();
        $user = UserModel::get($postData['uid']);
        // 1、创建关联表数据之前应该清除该用户权限数据，否则会在关联表继续建立关系，导致冗余数据。
        $user->auths()->detach();

            // 如果auth字段空，就只是清除所有角色
        if (empty($postData['auth'])){
            return json(['code'=>0, 'message'=>'所有角色清除']);
        }
        // 2、进行多对多关联数据绑定
        if ($user->auths()->attach($postData['auth'])) {
            return json(['code' => 0, 'message' => '角色分配成功']);
        }
        return json(['code' => 4000, 'message' => '角色分配失败']);
    }

    public function demo()
    {
        $user = UserModel::get(13);
        foreach ($user->auths as $auth) {
            dump($auth['permission']);
        }

        // $res = $user->auths()->detach();
        // if($res){
        //     echo "解除成功";
        // }
        // dump($res);
    }

}